﻿using B.Z.BasicData.API.Read.DTO;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;

namespace B.Z.BasicData.API.Read.Application.Menu
{
    public class MenuCascaderQueryCommandHandler : IRequestHandler<MenuCascaderQueryCommand, APIResult<List<CascaderDTO>>>
    {
        private readonly IBaseRepository<T_Menu> menuRepository;

        public MenuCascaderQueryCommandHandler(IBaseRepository<T_Menu> menuRepository)
        {
            this.menuRepository = menuRepository;
        }

        public Task<APIResult<List<CascaderDTO>>> Handle(MenuCascaderQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<CascaderDTO>> result = new APIResult<List<CascaderDTO>>();
            result.Code = APIEnum.ok;
            result.Message = "获取成功";
            result.Data = GetList(0);
            return Task.FromResult(result);

        }

        private List<CascaderDTO> GetList(int pid) 
        {
            List<CascaderDTO> dtos = new List<CascaderDTO>();
            var list = menuRepository.GetAll().Where(p => p.Pid == pid);
            foreach (var item in list)
            {
                CascaderDTO dTO = new()
                {
                    value=item.Id,
                    label=item.MenuName,
                    children= GetList(item.Id)
                };
                dtos.Add(dTO);
                
            }
            return dtos;
        }
    }
}
